package controller

import (
	"encoding/json"
	"gobase/app/model"
	"gobase/app/service"
	"gobase/util"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

//角色控制器
type RoleController struct {
	BaseController
}

//路由注册
func (ctl *RoleController) Router(router *gin.Engine) {
	r := router.Group("admin/role")
	r.GET("/list", ctl.queryList)
	r.GET("/add", ctl.add)
	r.POST("/add", ctl.add)

	r.GET("/edit/:id", ctl.edit)
	r.PUT("/edit/:id", ctl.edit)

	r.GET("/authorizeFunc/:id", ctl.authorizeFunc)
	r.POST("/authorizeFunc/:id", ctl.authorizeFunc)
	r.GET("/authorizeUser/:id", ctl.authorizeUser)
	r.POST("/authorizeUser/:id", ctl.authorizeUser)

	r.DELETE("/del/:id", ctl.del)
	//启用/禁用
	r.PATCH("/eord/:id/:state", ctl.enableOrDisable)
}

//列表
func (ctl *RoleController) queryList(c *gin.Context) {
	srv := service.NewRoleService(c)
	var p = util.GetPageParam(c)
	var qrolename = c.DefaultQuery("qrolename", "")

	resultp, roleList := srv.QueryList(p, qrolename)
	c.HTML(http.StatusOK, "role/list.html", gin.H{
		"title":     "角色列表",
		"qrolename": qrolename,
		"_page":     resultp,
		"dataList":  roleList,
		"flashmsg":  ctl.GetSessionFlash(c),
	})
}

//新增
func (ctl *RoleController) add(c *gin.Context) {
	if ctl.IsPost(c.Request.Method) {
		var message = ""
		var status = false

		role := new(model.Role)
		err := c.ShouldBind(role)
		if err != nil {
			message = util.GetValidMsg(err, model.Role{})
			ctl.ResponseJSON(c, status, message)
		}

		srv := service.NewRoleService(c)
		err = srv.Add(role)
		if err != nil {
			message = err.Error()
		} else {
			status = true
		}
		ctl.ResponseJSON(c, status, message)
	} else {
		c.HTML(http.StatusOK, "role/add.html", gin.H{
			"title": "添加角色",
		})
	}
}

//编辑
func (ctl *RoleController) edit(c *gin.Context) {
	idStr := c.Param("id")
	if idStr == "" {
		ctl.FlashMsg(c, "参数错误!")
		c.Redirect(http.StatusFound, "/role/list")
	}
	id, _ := strconv.Atoi(idStr)
	srv := service.NewRoleService(c)

	if ctl.IsPut(c.Request.Method) {
		var message = ""
		var status = false

		role := new(model.Role)
		err := c.ShouldBind(role)
		if err != nil {
			message = util.GetValidMsg(err, model.Role{})
			ctl.ResponseJSON(c, status, message)
		}

		err = srv.Update(id, role)
		if err != nil {
			message = err.Error()
		} else {
			status = true
		}
		ctl.ResponseJSON(c, status, message)
	} else {
		//查询角色信息
		roleInfo, _ := srv.GetByID(id)
		c.HTML(http.StatusOK, "role/edit.html", gin.H{
			"title": "修改角色",
			"role":  roleInfo,
		})
	}
}

//删除
func (ctl *RoleController) del(c *gin.Context) {
	var message = "删除失败："
	var status = false

	idStr := c.Param("id")
	if idStr == "" {
		message += "参数为空!"
		ctl.ResponseJSON(c, status, message)
	}

	id, _ := strconv.Atoi(idStr)
	err := service.NewRoleService(c).DeleteById(id)
	if err != nil {
		message = err.Error()
	} else {
		status = true
	}
	ctl.ResponseJSON(c, status, message)
}

//启用/禁用
func (ctl *RoleController) enableOrDisable(c *gin.Context) {
	var message = "启用失败："
	var status = false

	idStr := c.Param("id")
	stateStr := c.Param("state")
	if idStr == "" || stateStr == "" || (stateStr != "1" && stateStr != "0") {
		message += "参数错误!"
		ctl.ResponseJSON(c, status, message)
	}

	id, _ := strconv.Atoi(idStr)
	err := service.NewRoleService(c).EnableOrDisable(id, stateStr)
	if err != nil {
		message = err.Error()
	} else {
		status = true
	}
	ctl.ResponseJSON(c, status, message)
}

//关联权限
func (ctl *RoleController) authorizeFunc(c *gin.Context) {
	idStr := c.Param("id")
	if idStr == "" {
		ctl.FlashMsg(c, "参数错误!")
		c.Redirect(http.StatusFound, "/role/list")
	}
	id, _ := strconv.Atoi(idStr)

	if ctl.IsPost(c.Request.Method) {
		var status = false
		var message = ""
		resourceIds, _ := c.GetPostFormArray("resourceIds[]")
		err := service.NewRoleResourceService(c).AuthorizeFunc(id, resourceIds)
		if err != nil {
			message = err.Error()
		} else {
			status = true
		}

		ctl.ResponseJSON(c, status, message)
	} else {
		//查询角色信息
		roleInfo, _ := service.NewRoleService(c).GetByID(id)
		//角色已授权资源
		roleResList := service.NewRoleResourceService(c).GetRoleResourceList(id)
		jsonRoleResList, _ := json.Marshal(roleResList)
		c.HTML(http.StatusOK, "role/authorizeFunc.html", gin.H{
			"title":           "关联权限",
			"role":            roleInfo,
			"roleAuthResList": string(jsonRoleResList),
		})
	}
}

//授权用户
func (ctl *RoleController) authorizeUser(c *gin.Context) {
	idStr := c.Param("id")
	if idStr == "" {
		ctl.FlashMsg(c, "参数错误!")
		c.Redirect(http.StatusFound, "/role/list")
	}
	id, _ := strconv.Atoi(idStr)

	if ctl.IsPost(c.Request.Method) {
		var status = true
		var message = ""
		userIds, _ := c.GetPostFormArray("userIds[]")
		err := service.NewRoleUserService(c).AuthorizeUser(id, userIds)
		if err != nil {
			message = err.Error()
			status = false
		}
		ctl.ResponseJSON(c, status, message)
	} else {
		//查询角色信息
		roleInfo, _ := service.NewRoleService(c).GetByID(id)
		//角色已关联用户
		roleUserList := service.NewRoleUserService(c).GetRoleUserList(id)
		jsonRoleUserList, _ := json.Marshal(roleUserList)
		c.HTML(http.StatusOK, "role/authorizeUser.html", gin.H{
			"title":            "授权用户",
			"role":             roleInfo,
			"roleAuthUserList": string(jsonRoleUserList),
		})
	}
}
